package kingwing.dc.core.view.search;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.Entity;

import kingwing.dc.core.model.Infos;
import kingwing.dc.core.model.Rule;
import kingwing.dc.core.model.RuleDetail;
import kingwing.dc.core.orm.hibernate.CommonHibernateDao;

import org.apache.commons.lang.StringUtils;
import org.hibernate.classic.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.business.IUser;
import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.bdf2.core.exception.NoneLoginException;
import com.bstek.bdf2.core.orm.hibernate.HibernateDao;
import com.bstek.dorado.annotation.DataProvider;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import com.bstek.dorado.view.View;
import com.bstek.dorado.view.widget.Align;
import com.bstek.dorado.view.widget.base.Dialog;
import com.bstek.dorado.view.widget.base.FieldSet;
import com.bstek.dorado.view.widget.base.tab.TabControl;
import com.bstek.dorado.view.widget.form.TextArea;
import com.bstek.dorado.view.widget.grid.DataColumn;
import com.bstek.dorado.view.widget.grid.DataGrid;

@Component
public class SearchKeyWordPR  extends HibernateDao{
	@Resource(name=CommonHibernateDao.BEAN_ID)
	private CommonHibernateDao commonHibernateDao;
	
	/**
	 * 获取搜索网站
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public Collection<Map<String,Object>> getTrimsRules(String flag){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		String userName = user.getUsername();
		
		Session session = this.getSessionFactory().openSession();
		List<Map<String,Object>> rulesList =null;
		String hql=" select RULE_NAME_ as label,ID_ as code,RULE_NAME_ as ruleName, ID_ as id,"
				+ " SCAN_URLS_ as scanUrls ,DOMAINS_ as domains,CONTENT_URLS_ as contentUrls,"
				+ " CONTENT_ID_ as contentId,CONTENT_URL_REGEXES_ as contentUrlRegexes,"
				+ " HELPER_URL_REGEXES_ as helperUrlRegexes ,PAGE_TYPE_  as pageType,"
				+ " GRAB_TYPE_ as grabType from DC_RULE  where CHECK_=1 and CREATE_USER_ID_=:userName";
		try{
		     rulesList = session.createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setParameter("userName", userName).list();
		}finally{
			session.flush();
			session.close();
		}
		if(StringUtils.isEmpty(flag)){
			Map<String,Object> map=new HashMap<>();
			map.put("code", "code");
			map.put("label", "点击编辑搜索站点");
			rulesList.add(map);
		}
		return rulesList;
	}
	
	/**
	 * 获取搜索网站
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public Collection<Map<String,Object>> getSelectRules(String flag){
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		String userName = user.getUsername();
		Session session = this.getSessionFactory().openSession();
		List<Map<String,Object>> rulesList =null;
		String hql=" select RULE_NAME_ as label,ID_ as code,RULE_NAME_ as ruleName, ID_ as id,"
				+ " SCAN_URLS_ as scanUrls ,DOMAINS_ as domains,CONTENT_URLS_ as contentUrls,"
				+ " CONTENT_ID_ as contentId,CONTENT_URL_REGEXES_ as contentUrlRegexes,"
				+ " HELPER_URL_REGEXES_ as helperUrlRegexes ,PAGE_TYPE_  as pageType,"
				+ " GRAB_TYPE_ as grabType  from DC_RULE  where CHECK_=1 and CREATE_USER_ID_=:userName";
		try{
		     rulesList = session.createSQLQuery(hql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setParameter("userName", userName).list();
		}finally{
			session.flush();
			session.close();
		}
		
		return rulesList;
	}
	
	/**
	 * 获取网站
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public Collection<Rule> getRules(){
		
		IUser user = ContextHolder.getLoginUser();
		if (user == null) {
			throw new NoneLoginException("登陆超时，请登录！");
		}
		String userName = user.getUsername();
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Rule.class);
		
		detachedCriteria.add(Restrictions.and( Restrictions.eq("createUserId", userName), 
				Restrictions.eq("check", false)));
		
		return (Collection<Rule>) this.commonHibernateDao.query(detachedCriteria);
	}
	
	/**
	 * 添加搜索网站
	 * @param ids
	 * @return
	 */
	@Transactional
	@Expose
	public String updateCheck(List<String> ids){
		int count=0;
		Session session = this.getSessionFactory().openSession();
		try{
			for (String id : ids) {
				String sql="update DC_RULE set CHECK_=1 where ID_='"+id+"'";
				int res=session.createSQLQuery(sql).executeUpdate();
				if(res>0) count++;
			}
		}finally{
			session.flush();
			session.close();
		}
		if(count==ids.size()){
			return "添加成功";
		}else{
			return "添加成功["+count+"]个";
		}
	}
	
	/**
	 * 取消搜索网站
	 * @param ids
	 * @return
	 */
	@Transactional
	@Expose
	public String cancelCheck(List<String> ids){
		int count=0;
		Session session = this.getSessionFactory().openSession();
		try{
			for (String id : ids) {
				String sql="update DC_RULE set CHECK_=0 where ID_='"+id+"'";
				int res=session.createSQLQuery(sql).executeUpdate();
				if(res>0) count++;
			}
		}finally{
			session.flush();
			session.close();
		}
		if(count==ids.size()){
			return "操作成功";
		}else{
			return "操作成功["+count+"]个";
		}
	}
	
	/**
	 * 依据规则名称、关键字分页获取采集信息
	 * @param page
	 */
	@SuppressWarnings("unchecked")
	@DataProvider
	public void getInfosPage(Page<Infos> page,Map<String, Object> params ){
		
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Infos.class);
		Disjunction disjunction = Restrictions.disjunction();
		List<Rule> rules = new ArrayList<Rule>();
		String text = "";
		if (!params.isEmpty() && params!=null) {
			rules =  (List<Rule>) params.get("rule");
			text = params.get("text").toString();
			
		}else{
			return;
		}
		
		if (rules != null) {
			for (Rule rule : rules) {
				String ruleName =EntityUtils.getValue(rule,"label");
				if(ruleName.equals("点击添加站点")){
					continue;
				}
				disjunction.add(Restrictions.eq("ruleName", ruleName));
			}
		}
		
		if (StringUtils.isNotBlank(text)) {
			detachedCriteria.add(Restrictions.or(Restrictions.ilike("field1", "%"+text+"%"),
					Restrictions.ilike("field2", "%"+text+"%")));
		}
		
		detachedCriteria.add(disjunction);
		detachedCriteria.add(Restrictions.eq("createUserId", ContextHolder.getLoginUserName()));
		detachedCriteria.addOrder(Order.desc("field3"));
		
		this.commonHibernateDao.pagingQuery(page, detachedCriteria);
	}
	
}
